package collection.MyList;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author
 * @Description:
 */
public class MyLinkedList {
    static class ListNode{
        private int val;
        private ListNode prev;
        private ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;
    public ListNode last;

    public void display(){
        ListNode cur = head;
        while(cur != null){
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }
    public int size(){
        ListNode cur = head;
        int count = 0;
        while(cur != null){
            count++;
            cur = cur.next;
        }
        return count;
    }
    //头插法
    public void addFirst(int data){
        ListNode node = new ListNode(data);
        if (head == null){
            head = node;
            last = node;
        }else {
            node.next = head;
            head.prev = node;
            head = node;
        }

    }
    //尾插法
    public void addLast(int data){
        ListNode node = new ListNode(data);
        if (last == null){
            head = node;
            last = node;
        }else {
            node.prev = last;
            last.next = node;
            last = node;
        }
    }
    /**
     *
     */
    public void addIndex(int data,int index) {
        checkIndex(index);
        if (index == 0) {
            addFirst(data);
            return;
        }
        if (index == size()) {
            addLast(data);
            return;
        }
        ListNode node = new ListNode(data);
        ListNode cur = searcIndex(index);
        node.next = cur;
        cur.prev.next = node;
        node.prev = cur.prev;
        cur.prev = node;
        //node.prev = cur.prev;
        //node.prev.next = node;
        //node.next = cur;
        //cur.prev = node;
    }
    public ListNode searcIndex(int index){
        ListNode cur = head;
        while (index != 0){
            cur = cur.next;
            index--;
        }
        return cur;
    }
    public void checkIndex(int index){
        if (index < 0 || index > size()){
            throw new IndexOutOfException("index不合法" + index);
        }
    }
    public void removeIndex(int index){
        checkIndex(index);
        ListNode cur = searcIndex(index);
        cur.prev.next = cur.next;
        cur.next.prev = cur.prev;
    }
    public void clean(){
        ListNode cur = head;
        while (cur!=null){
            cur.prev = null;
            cur = cur.next;
        }
    }
}
